package com.study.springcloud.config;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author Chen Jie
 * @Date 2022/3/7 19:08
 * @Version 1.0
 */
@Slf4j
public class MyRule extends AbstractLoadBalancerRule {
    private AtomicInteger integer = new AtomicInteger(0);

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object key) {
        log.info("执行了自定义的负载均衡算法...");
        ILoadBalancer lb = getLoadBalancer();
        if (lb == null) {
            return null;
        }

        List<Server> allList = lb.getAllServers();
        int serverCount = allList.size();
        if (serverCount == 0) {
            return null;
        }

        while(true) {
            int currentIndex = integer.get();
            int nextIndex = (1 + currentIndex) % serverCount;
            if(integer.compareAndSet(currentIndex, nextIndex)) {
                return allList.get(nextIndex);
            }
        }
    }
}
